/**
 * 数据导入导出功能
 * 支持医院管理系统的数据导入导出
 */

import { hospitalDB } from './indexedDB'
import { toast } from 'sonner'

// 支持的文件格式
export type SupportedFormat = 'json' | 'csv' | 'excel'

// 导出配置
export interface ExportConfig {
  filename: string
  format: SupportedFormat
  data: any[]
  headers?: string[]
}

// 导入结果
export interface ImportResult {
  success: boolean
  data?: any[]
  error?: string
  count?: number
}

/**
 * 导出数据为JSON格式
 */
export async function exportToJSON(data: any[], filename: string): Promise<void> {
  try {
    const jsonData = JSON.stringify(data, null, 2)
    const blob = new Blob([jsonData], { type: 'application/json;charset=utf-8' })
    downloadFile(blob, `${filename}.json`)
  } catch (error) {
    console.error('JSON导出失败:', error)
    throw new Error('JSON导出失败')
  }
}

/**
 * 导出数据为CSV格式
 */
export async function exportToCSV(data: any[], filename: string, headers?: string[]): Promise<void> {
  try {
    if (!data || data.length === 0) {
      throw new Error('没有数据可导出')
    }

    const csvHeaders = headers || Object.keys(data[0])
    
    // 函数：格式化CSV单元格值，正确处理复杂对象
    const formatCSVCellValue = (value: any): string => {
      if (value === null || value === undefined) {
        return ''
      }
      
      if (typeof value === 'object') {
        if (Array.isArray(value)) {
          return value.length > 0 ? JSON.stringify(value) : '[]'
        } else {
          // 对象类型，转换为JSON字符串
          return JSON.stringify(value)
        }
      }
      
      const stringValue = String(value)
      // 处理包含逗号、引号或换行符的值
      if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\n')) {
        return `"${stringValue.replace(/"/g, '""')}"`
      }
      
      return stringValue
    }
    
    const csvRows = data.map(row => 
      csvHeaders.map(header => formatCSVCellValue(row[header])).join(',')
    )
    
    const csvContent = [csvHeaders.join(','), ...csvRows].join('\n')
    
    // 添加BOM支持中文
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8' })
    downloadFile(blob, `${filename}.csv`)
  } catch (error) {
    console.error('CSV导出失败:', error)
    throw new Error('CSV导出失败')
  }
}

/**
 * 导出数据为Excel格式
 */
export async function exportToExcel(data: any[], filename: string, headers?: string[]): Promise<void> {
  try {
    if (!data || data.length === 0) {
      throw new Error('没有数据可导出')
    }

    const excelHeaders = headers || Object.keys(data[0])
    
    // 函数：格式化单元格值，正确处理复杂对象
    const formatCellValue = (value: any): string => {
      if (value === null || value === undefined) {
        return ''
      }
      
      if (typeof value === 'object') {
        if (Array.isArray(value)) {
          return value.length > 0 ? JSON.stringify(value) : '[]'
        } else {
          // 对象类型，转换为JSON字符串
          return JSON.stringify(value)
        }
      }
      
      if (typeof value === 'string') {
        // HTML转义
        return value
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;')
      }
      
      return String(value)
    }
    
    // 创建简单的HTML表格格式，Excel可以识别
    const htmlTable = `
      <table border="1">
        <thead>
          <tr>
            ${excelHeaders.map(header => `<th style="background-color: #f0f0f0; font-weight: bold;">${header}</th>`).join('')}
          </tr>
        </thead>
        <tbody>
          ${data.map(row => 
            `<tr>
              ${excelHeaders.map(header => `<td>${formatCellValue(row[header])}</td>`).join('')}
            </tr>`
          ).join('')}
        </tbody>
      </table>
    `

    const blob = new Blob([htmlTable], { type: 'application/vnd.ms-excel;charset=utf-8' })
    downloadFile(blob, `${filename}.xls`)
  } catch (error) {
    console.error('Excel导出失败:', error)
    throw new Error('Excel导出失败')
  }
}

/**
 * 通用文件下载函数
 */
function downloadFile(blob: Blob, filename: string): void {
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = filename
  
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  // 清理URL对象
  setTimeout(() => URL.revokeObjectURL(link.href), 100)
}

/**
 * 从文件导入JSON数据
 */
export async function importFromJSON(file: File): Promise<ImportResult> {
  try {
    const text = await file.text()
    const data = JSON.parse(text)
    
    if (!Array.isArray(data)) {
      throw new Error('JSON文件必须包含数组格式的数据')
    }
    
    return {
      success: true,
      data,
      count: data.length
    }
  } catch (error) {
    console.error('JSON导入失败:', error)
    return {
      success: false,
      error: `JSON导入失败: ${error}`
    }
  }
}

/**
 * 从文件导入Excel数据 (简单的HTML表格解析)
 */
export async function importFromExcel(file: File): Promise<ImportResult> {
  try {
    const text = await file.text()
    
    // 简单的HTML表格解析（适用于我们导出的Excel格式）
    const tableMatch = text.match(/<table[^>]*>(.*?)<\/table>/is)
    if (!tableMatch) {
      throw new Error('Excel文件格式不正确，无法找到表格数据')
    }
    
    const tableContent = tableMatch[1]
    
    // 提取表头
    const theadMatch = tableContent.match(/<thead[^>]*>(.*?)<\/thead>/is)
    if (!theadMatch) {
      throw new Error('Excel文件格式不正确，无法找到表头')
    }
    
    const headerRowMatch = theadMatch[1].match(/<tr[^>]*>(.*?)<\/tr>/is)
    if (!headerRowMatch) {
      throw new Error('Excel文件格式不正确，无法解析表头行')
    }
    
    const headerCells = headerRowMatch[1].match(/<th[^>]*>(.*?)<\/th>/gis)
    if (!headerCells) {
      throw new Error('Excel文件格式不正确，无法解析表头单元格')
    }
    
    const headers = headerCells.map(cell => {
      return cell.replace(/<[^>]+>/g, '').trim()
    })
    
    // 提取数据行
    const tbodyMatch = tableContent.match(/<tbody[^>]*>(.*?)<\/tbody>/is)
    if (!tbodyMatch) {
      throw new Error('Excel文件格式不正确，无法找到数据体')
    }
    
    const dataRows = tbodyMatch[1].match(/<tr[^>]*>(.*?)<\/tr>/gis)
    if (!dataRows) {
      return {
        success: true,
        data: [],
        count: 0
      }
    }
    
    const data = dataRows.map(row => {
      const cells = row.match(/<td[^>]*>(.*?)<\/td>/gis) || []
      const rowData: any = {}
      
      headers.forEach((header, index) => {
        let value = ''
        if (cells[index]) {
          value = cells[index]
            .replace(/<[^>]+>/g, '')
            .replace(/&amp;/g, '&')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&quot;/g, '"')
            .trim()
        }
        
        // 尝试解析JSON格式的复杂对象
        if (value && (value.startsWith('{') || value.startsWith('['))) {
          try {
            rowData[header] = JSON.parse(value)
          } catch {
            // 如果解析失败，保持原始字符串
            rowData[header] = value
          }
        } else {
          rowData[header] = value
        }
      })
      
      return rowData
    })
    
    return {
      success: true,
      data,
      count: data.length
    }
  } catch (error) {
    console.error('Excel导入失败:', error)
    return {
      success: false,
      error: `Excel导入失败: ${error}`
    }
  }
}

/**
 * 从文件导入CSV数据
 */
export async function importFromCSV(file: File): Promise<ImportResult> {
  try {
    const text = await file.text()
    const lines = text.split('\n').filter(line => line.trim())
    
    if (lines.length < 2) {
      throw new Error('CSV文件至少需要包含标题行和一行数据')
    }
    
    const headers = lines[0].split(',').map(h => h.trim().replace(/"/g, ''))
    const data = lines.slice(1).map(line => {
      const values = parseCSVLine(line)
      const row: any = {}
      headers.forEach((header, index) => {
        let value = values[index] || ''
        
        // 尝试解析JSON格式的复杂对象
        if (value && (value.startsWith('{') || value.startsWith('['))) {
          try {
            row[header] = JSON.parse(value)
          } catch {
            // 如果解析失败，保持原始字符串
            row[header] = value
          }
        } else {
          row[header] = value
        }
      })
      return row
    })
    
    return {
      success: true,
      data,
      count: data.length
    }
  } catch (error) {
    console.error('CSV导入失败:', error)
    return {
      success: false,
      error: `CSV导入失败: ${error}`
    }
  }
}

/**
 * 解析CSV行，处理逗号和引号
 */
function parseCSVLine(line: string): string[] {
  const result = []
  let current = ''
  let inQuotes = false
  
  for (let i = 0; i < line.length; i++) {
    const char = line[i]
    const nextChar = line[i + 1]
    
    if (char === '"') {
      if (inQuotes && nextChar === '"') {
        // 转义的引号
        current += '"'
        i++ // 跳过下一个引号
      } else {
        // 开始或结束引号
        inQuotes = !inQuotes
      }
    } else if (char === ',' && !inQuotes) {
      // 字段分隔符
      result.push(current.trim())
      current = ''
    } else {
      current += char
    }
  }
  
  result.push(current.trim())
  return result
}

/**
 * 导出医院数据
 */
export async function exportHospitalData(format: SupportedFormat = 'json'): Promise<void> {
  try {
    // 确保数据库已初始化
    await hospitalDB.initPromise
    
    const hospitals = await hospitalDB.getAll('hospitals')
    const departments = await hospitalDB.getAll('departments') 
    const medical_equipment = await hospitalDB.getAll('medical_equipment')
    
    const exportData = {
      hospitals,
      departments,
      medical_equipment,
      exportTime: new Date().toISOString(),
      version: '1.0'
    }
    
    const filename = `医院数据_${new Date().toLocaleDateString().replace(/\//g, '-')}`
    
    switch (format) {
      case 'json':
        await exportToJSON([exportData], filename)
        break
      case 'csv':
        // CSV格式导出所有表的汇总
        const allData = [
          ...hospitals.map(h => ({ ...h, 数据类型: '医院' })),
          ...departments.map(d => ({ ...d, 数据类型: '科室' })),
          ...medical_equipment.map(e => ({ ...e, 数据类型: '设备' }))
        ]
        await exportToCSV(allData, filename)
        break
      case 'excel':
        const allDataExcel = [
          ...hospitals.map(h => ({ ...h, 数据类型: '医院' })),
          ...departments.map(d => ({ ...d, 数据类型: '科室' })),
          ...medical_equipment.map(e => ({ ...e, 数据类型: '设备' }))
        ]
        await exportToExcel(allDataExcel, filename)
        break
    }
    
    toast.success(`医院数据已导出为${format.toUpperCase()}格式`)
  } catch (error) {
    console.error('导出医院数据失败:', error)
    toast.error('导出医院数据失败')
    throw error
  }
}

/**
 * 导入医院数据
 */
export async function importHospitalData(file: File): Promise<ImportResult> {
  try {
    let importResult: ImportResult
    
    if (file.name.endsWith('.json')) {
      importResult = await importFromJSON(file)
    } else if (file.name.endsWith('.csv')) {
      importResult = await importFromCSV(file)
    } else if (file.name.endsWith('.xls') || file.name.endsWith('.xlsx')) {
      importResult = await importFromExcel(file)
    } else {
      return {
        success: false,
        error: '不支持的文件格式，请使用JSON、CSV或Excel文件'
      }
    }
    
    if (!importResult.success || !importResult.data) {
      return importResult
    }
    
    // 处理导入的数据
    const data = importResult.data
    let totalImported = 0
    
    // 确保数据库已初始化
    await hospitalDB.initPromise
    
    // 如果是完整的医院数据导出格式
    if (data.length === 1 && data[0].hospitals && data[0].departments && (data[0].medical_equipment || data[0].equipment)) {
      const hospitalData = data[0]
      
      // 导入医院数据 - 使用upsert避免重复键冲突
      if (hospitalData.hospitals?.length) {
        for (const hospital of hospitalData.hospitals) {
          await hospitalDB.upsert('hospitals', hospital)
        }
        totalImported += hospitalData.hospitals.length
      }
      
      // 导入科室数据 - 使用upsert避免重复键冲突
      if (hospitalData.departments?.length) {
        for (const department of hospitalData.departments) {
          await hospitalDB.upsert('departments', department)
        }
        totalImported += hospitalData.departments.length
      }
      
      // 导入设备数据（支持新旧字段名） - 使用upsert避免重复键冲突
      const equipmentData = hospitalData.medical_equipment || hospitalData.equipment
      if (equipmentData?.length) {
        for (const equipment of equipmentData) {
          await hospitalDB.upsert('medical_equipment', equipment)
        }
        totalImported += equipmentData.length
      }
    } else {
      // 处理单独的数据表格 - 使用upsert避免重复键冲突
      for (const item of data) {
        if (item.数据类型 === '医院') {
          delete item.数据类型
          await hospitalDB.upsert('hospitals', item)
        } else if (item.数据类型 === '科室') {
          delete item.数据类型
          await hospitalDB.upsert('departments', item)
        } else if (item.数据类型 === '设备') {
          delete item.数据类型
          await hospitalDB.upsert('medical_equipment', item)
        }
        totalImported++
      }
    }
    
    return {
      success: true,
      count: totalImported
    }
  } catch (error) {
    console.error('导入医院数据失败:', error)
    return {
      success: false,
      error: `导入医院数据失败: ${error}`
    }
  }
}

/**
 * 创建文件上传组件的配置
 */
export function createFileUploadConfig(onFileSelected: (file: File) => void) {
  return {
    accept: '.json,.csv,.xls,.xlsx',
    onChange: (event: React.ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files?.[0]
      if (file) {
        onFileSelected(file)
      }
    }
  }
}